package com.app.controller;

import com.app.model.*;
import com.app.service.AdminUserService;
import com.app.service.CarService;
import com.app.service.CategoryService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.CarVo;
import com.app.vo.CategoryVo;
import com.app.vo.TaskVo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 车辆信息管理
 */
@RestController
@Controller
@RequestMapping("/api/car")
public class CarController {
    @Autowired
    private CarService carService;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/getDropList")//下拉框查询
    public Result<Object> getDropList(
            HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        CategoryVo vo = new CategoryVo();
        List<CategoryModel> categoryModelList = categoryService.getCategoryByPid(126);
        vo.setTypeList(categoryModelList);//型号类型
        List<CategoryModel> categoryModelList1 = categoryService.getCategoryByPid(122);
        vo.setStatusList(categoryModelList1);
        return Result.success(vo);
    }

    //新增和编辑
    @PostMapping("/insertCar")
    public Result<Object> insertCar(@RequestBody CarModel carModel, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        if (carModel.getId() > 0) {
            carModel.setUpdateTime(CommonHelp.getNowTimestamp());
            carService.update(carModel);
        } else {
            carModel.setCreateTime(CommonHelp.getNowTimestamp());
            carService.insert(carModel);
        }
        return Result.success("操作成功");
    }

    //删除
    @GetMapping("/deleteCar")
    public Result<Object> deleteCar(Integer id, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        carService.delete(id);
        return Result.success("操作成功");
    }


    //批量删除车辆信息
    @DeleteMapping("/deleteCarBatchByIds")
    public Result<Object> deleteCarBatchByIds(@RequestParam("ids") String ids, HttpServletRequest request){
        // 校验token并获取用户信息
        AdminUserModel user = validateTokenAndGetUser(request);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        return carService.deleteCarBatchByIds(ids);
    }

    //查询列表
    @GetMapping("/selectCar")
    public Result<Object> selectCar(Integer page, Integer limit, String carNumber, HttpServletRequest request,Integer sortType) {
        // 校验token并获取用户信息
        AdminUserModel user = validateTokenAndGetUser(request);
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        CarVo vo = new CarVo();
        Page<CarModel> taskModelPage = carService.selectCarList(page, limit, carNumber,sortType);
        List<CarModel> records = taskModelPage.getRecords();
        for (int i = 0; i < records.size(); i++) {
            Integer type = records.get(i).getType();
            if (type!=null){
                CategoryModel categoryById = categoryService.getCategoryById(records.get(i).getType());
                records.get(i).setTypeText(categoryById.getName());
            }
            Integer status = records.get(i).getStatus();
            if (status!=null){
                CategoryModel categoryById1 = categoryService.getCategoryById(records.get(i).getStatus());
                records.get(i).setStatusText(categoryById1.getName());
            }
        }
        int total = (int) taskModelPage.getTotal();
        vo.setList(records);
        vo.setCount(total);
        return Result.success(vo);
    }


    // 校验token并获取用户信息的方法
    private AdminUserModel validateTokenAndGetUser(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            throw new IllegalArgumentException("token不存在");
        }
        String userId = TokenUtils.verify(token);
        return adminUserService.getUserByUserId(Integer.parseInt(userId));
    }
}
